//
//  UIViewController+QSExtension.swift
//  TestSwift
//
//  Created by Song on 2018/10/31.
//  Copyright © 2018 Song. All rights reserved.
//

import UIKit

extension UIViewController: UIGestureRecognizerDelegate {
    /// 设置导航栏的shadowImage，默认隐藏
    ///
    /// - Parameters:
    ///   - need: 是否需要shadowImage
    ///   - color: shadowImage颜色，隐藏时，设置颜色无效
    func qs_setNavBarShadowImage(hidden: Bool = true, color: UIColor) {
        guard let nav = self.navigationController else { return }
        
        if !hidden {
            nav.navigationBar.shadowImage = self.qs_createImage(solidColor: color, size: CGSize.init(width: UIScreen.main.bounds.size.width, height: 10.0))
        } else {
            nav.navigationBar.setBackgroundImage(UIImage(), for: .default)
            nav.navigationBar.shadowImage = UIImage.init()
        }
    }
    
    /// 设置TabBar的shadowImage是否隐藏
    /// 必须要在子控制器中设置才有效
    /// - Parameters:
    ///   - need: 是否需要shadowImage
    ///   - color: shadowImage颜色，默认白色
    func qs_setTabBarShadowImage(hidden: Bool = true) {
        guard let tabVc = self.tabBarController else { return }
        
        tabVc.tabBar.subviews[0].subviews[1].isHidden = hidden
    }
    
    /// 设置穿透导航栏
    ///
    /// - Parameters:
    ///   - extend: 是否需要穿透导航栏
    func qs_setExtendNavLayout(isExtend: Bool = false) {
        guard let nav = self.navigationController else { return }
        
        if isExtend {
            nav.navigationBar.isTranslucent = true
            
            self.navBarBgAlpha = 0.0
            self.automaticallyAdjustsScrollViewInsets = false
            self.edgesForExtendedLayout = UIRectEdge.top
        } else {
            nav.navigationBar.isTranslucent = true
            
            self.navBarBgAlpha = 1.0
            self.edgesForExtendedLayout = UIRectEdge()
            self.automaticallyAdjustsScrollViewInsets = false
        }
    }
    
    /// 设置穿透tabBar
    ///
    /// - Parameters:
    ///   - extend: 是否需要穿透tabBar
    func qs_setExtendTabBarLayout(isExtend: Bool = false) {
        if isExtend {
            self.automaticallyAdjustsScrollViewInsets = false
            self.edgesForExtendedLayout = UIRectEdge.bottom
        } else {
            self.edgesForExtendedLayout = UIRectEdge()
            self.automaticallyAdjustsScrollViewInsets = false
        }
    }
    
    /// 设置导航栏的背景颜色
    ///
    /// - Parameter color: 背景颜色
    func qs_setNavBarBackgroundColor(_ color: UIColor) {
        guard let nav = self.navigationController else { return }
        
        nav.navBarBgAlpha = 0
        nav.navigationBar.barTintColor = color
    }
    
    /// 设置导航栏的背景图片
    ///
    /// - Parameter imageName: 背景图片名
    func qs_setNavBarBackgroundImage(_ imageName: String) {
        guard let nav = self.navigationController else { return }
        
        nav.navigationBar.setBackgroundImage(UIImage.init(named: imageName), for: UIBarMetrics.default)
    }
    
    /// 导航栏是否使用大标题
    ///
    /// - Parameter isUse: 是否使用
    func qs_useNavLargeTitle(_ isUse: Bool) {
        guard let nav = self.navigationController else { return }
        
        if #available(iOS 11.0, *) {
            nav.navigationBar.prefersLargeTitles = isUse
        }
    }
    
    /// 设置导航栏title的字体大小和颜色
    ///
    /// - Parameters:
    ///   - font: 字体大小
    ///   - textColor: 字体颜色
    func qs_setNavTitle(font: UIFont = UIFont.systemFont(ofSize: 17.0), textColor: UIColor = .black) {
        guard let nav = self.navigationController else { return }
        
        let navBar = nav.navigationBar
        // 去除透明
        navBar.isTranslucent = false
        navBar.titleTextAttributes = [NSAttributedStringKey.font : font, NSAttributedStringKey.foregroundColor : textColor]
    }
    
    /// 设置导航栏的按钮颜色
    ///
    /// - Parameters:
    ///   - font: 字体大小
    ///   - textColor: 字体颜色
    func qs_setNavBtnColor(color: UIColor = .black) {
        guard let nav = self.navigationController else { return }
        nav.navigationBar.tintColor = color
    }
    
    /// 设置导航栏largeTitle的字体大小和颜色
    ///
    /// - Parameters:
    ///   - font: 字体大小
    ///   - textColor: 字体颜色
    func qs_setNavLargeTitle(font: UIFont?, textColor: UIColor = .black) {
        if #available(iOS 11.0, *) {
            guard let nav = self.navigationController else { return }
            
            let navBar = nav.navigationBar
            if navBar.prefersLargeTitles {
                var attDict = Dictionary<NSAttributedStringKey, Any>.init()
                attDict[NSAttributedStringKey.foregroundColor] = textColor
                
                if font != nil {
                    attDict[NSAttributedStringKey.font] = font!
                }
                
                navBar.largeTitleTextAttributes = attDict
            }
        }
    }
    
    /// 是否隐藏导航栏
    ///
    /// - Parameters:
    ///   - hidden: 是否隐藏
    ///   - animated: 动画
    func qs_hideNavBar(_ hidden: Bool, animated: Bool) {
        guard let nav = self.navigationController else { return }
        
        nav.setNavigationBarHidden(hidden, animated: animated)
    }
    
    // MARK: - Private Methods
    /// 设置返回按钮
    ///
    /// - Parameters:
    ///   - img: 图片名
    ///   - title: 文字
    ///   - titleColor: 文字颜色
    ///   - titleFont: 文字字体
    func qs_setReturnBtn(img: String?, title: String?, titleColor: UIColor?, titleFont: UIFont?) {
        let btnImg = UIImage.init(named: img ?? "")
        let btnWidth = self.qs_obtainTextWidthWith(text: title ?? "", font: titleFont ?? UIFont.systemFont(ofSize: 15.0), height: 20.0) + (btnImg?.size.width ?? 0.0)
        let btnHeight = btnImg?.size.width ?? 25.0
        if btnWidth < 25.0 {
            btnWidth = 25.0
        }
        
        let retBtn = UIButton.init(frame: CGRect.init(x: 0, y: 0, width: btnWidth, height: btnHeight))
        retBtn.setImage(UIImage.init(named: img ?? ""), for: .normal)
        retBtn.setTitle(title ?? "", for: .normal)
        retBtn.setTitleColor(titleColor ?? .black, for: .normal)
        retBtn.titleLabel?.font = titleFont
        retBtn.addTarget(self, action: #selector(self.qs_back), for: .touchUpInside)

        let btnItem = UIBarButtonItem.init(customView: retBtn)
        self.navigationItem.setLeftBarButton(btnItem, animated: true)
        
        self.navigationController?.interactivePopGestureRecognizer?.delegate = self
    }
    
    /// 返回pop
    @objc func qs_back() {
        self.navigationController?.popViewController(animated: true)
    }
    
    /// 生成一张纯色的图片
    ///
    /// - Parameters:
    ///   - solidColor: 图片颜色
    ///   - size: 图片大小
    /// - Returns: 返回图片
    private func qs_createImage(solidColor: UIColor, size: CGSize) -> UIImage? {
        
        let rect = CGRect.init(origin: CGPoint.init(x: 0, y: 0), size: size)
        UIGraphicsBeginImageContext(size)
        
        let context = UIGraphicsGetCurrentContext()
        context?.setFillColor(solidColor.cgColor)
        context?.fill(rect)
        
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        return image
    }
    
    /// 获取字符串的宽度
    ///
    /// - Parameters:
    ///   - text: 字符串
    ///   - font: 字符串字体
    ///   - height: 字符串的高
    /// - Returns: 宽
    private func qs_obtainTextWidthWith(text: String, font : UIFont, height : CGFloat) -> CGFloat {
        let attributes = [NSAttributedStringKey.font:font] //设置字体大小
        let option = NSStringDrawingOptions.usesLineFragmentOrigin
        
        let rect : CGRect = text.boundingRect(with: CGSize.init(width: CGFloat.greatestFiniteMagnitude, height: height), options: option, attributes: attributes, context: nil)
        
        return rect.width
    }
}
